package cn.tsingyu.spring.example.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;










import cn.tsingyu.spring.example.entity.User;

@Repository
public class UserDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public User getUser(final String username,String password){
		String sql = " select user_id,user_name from user where uname=? ";
		final User user = new User();
		jdbcTemplate.query(sql, new Object[]{username},
				new RowCallbackHandler(){
					public void processRow(ResultSet rs) throws SQLException{
						user.setUserId(rs.getInt("id"));
						user.setUsername(username);
					}
				});
		return user;
	}
	
	/**
	 * 通过用户名查询角色信息
	 * @param userName
	 * @return
	 */
	public Set<String> getRoles(String username) {
		String sql = "select r.name from user u,role r,user_role ur where u.id=ur.userId and r.id=ur.roleId and u.uname=?";
		final Set<String> roles = new HashSet<>();
		jdbcTemplate.query(sql,  new Object[]{username},
				new RowCallbackHandler(){
				public void processRow(ResultSet rs) throws SQLException{
					while(rs.next()){
						roles.add(rs.getString(1));
					}
				}
		});
		return roles;
	}
	
	/**
	 * 通过用户名查询权限信息
	 * @param userName
	 * @return
	 */
	public Set<String> getPermissions(String username) {
		String sql = "select res.name from user u,role r,user_role ur,role_resource rr,resource res where u.id=ur.userId and ur.roleId=r.id and u.id=ur.userId and r.id=rr.roleId and res.id=rr.resourceId and u.uname=?";
		final Set<String> permissions = new HashSet<>();
		Object[] args = new Object[]{username};
		RowCallbackHandler rch = new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				while(rs.next()){
					permissions.add(rs.getString(1));
				}
				
			}
		};
		jdbcTemplate.query(sql, args, rch);
		return null;
	}

	public User getByUserName(String username) {
		String sql = " select * from user where uname=? ";
		final User user = new User();
		jdbcTemplate.query(sql, new Object[]{username},
				new RowCallbackHandler(){
					public void processRow(ResultSet rs) throws SQLException{
						user.setUserId(rs.getInt("id"));
						user.setUsername(rs.getString("uname"));
						user.setPassword(rs.getString("pwd"));
					}
				});
		return user;
	}

}
